import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Image} from '@tarojs/components';
import {AtModal, AtModalAction, AtModalContent, AtModalHeader} from 'taro-ui';
import {newHttp} from "../../../utils/request";
import {
  NEW_GET_ORDER_DETAIL,
  AIKUCUN_ORDER_AFTERSALEDETAIL,
  AIKUCUN_ORDER_USERCONFIRMREFUNDMONEY,
  AIKUCUN_ORDER_CANCELAFTERSALE,
  CONTENT_QR
} from "../../../constants/api";
import {GetRequest} from "../../../utils/tools";
import Float from "../../../components/float/float";
import {http} from "../../../utils/http";
import './orderdetail.scss'

export default class Type extends Component {
  state: {
    orderInfo: object
    refundInfo: object
    refundReason: any
    type: number
    modalShow: boolean
    qrImg: string
  } = {
    orderInfo: {},
    refundInfo: {},
    refundReason: [
      {value: 0, label: '不想要了(无理由)'},
      {value: 1, label: '商品漏发'},
      {value: 2, label: '质量问题'},
      {value: 3, label: '发错款号'},
      {value: 4, label: '发错颜色'},
      {value: 5, label: '发错尺码'}],
    type: 0,
    modalShow: false,
    qrImg: '',
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV == 'h5') {
      const root = document.querySelector('.taro-tabbar__panel')
      root.style.backgroundColor = '#f3f3f3'
      /*root.onscroll = debounce((page) => {
        this.setState({scrollTop: page[0].target.scrollTop})
      }, 10)*/
    }

    const { orderId, type } = Taro.getCurrentInstance().router.params
    const orderInfo = await newHttp.catchGet(NEW_GET_ORDER_DETAIL, {orderId})
    const refundInfo = await http.HPost(AIKUCUN_ORDER_AFTERSALEDETAIL, {order_num: orderId})
    if (orderInfo) {
      this.setState({orderInfo: orderInfo, refundInfo: refundInfo.data, type: type})
    }
  }

  getReasonName(id) {
    const goodsSite = this.state.refundReason.filter(item => item.value == id);
    const label = goodsSite.length > 0 ? goodsSite[0].label : '';
    return label;
  }

  async sureRefundPrice(item, flag) {
    // flag: 1确认当前金额，2拒绝当前金额
    const { orderId } = Taro.getCurrentInstance().router.params
    const params = {
      after_sale_form_id: item.id,
      is_accept: flag
    }
    const ret = await http.HPost(AIKUCUN_ORDER_USERCONFIRMREFUNDMONEY, params)
    if (ret && ret.data === '操作完成') {
      Taro.showToast({title: '提交成功'});
      const timer = setTimeout(() => {
        clearTimeout(timer);
        Taro.navigateTo({ url: '/main/order/aftersales/orderdetail?orderId=' + orderId  })
      }, 1500);
      // const timer = setTimeout(() => {
      //   clearTimeout(timer);
      //   Taro.navigateBack({
      //     delta: 1
      //   });
      // }, 1500);
    }
  }

  copy(value) {
    if (value) {
      try {
        Taro.setClipboardData({
          data: value
        })
        if (process.env.TARO_ENV === 'h5') {
          Taro.showToast({title: '复制成功'})
        }
      } catch (e) {
        Taro.showToast({title: '复制失败', icon: 'none'})
      }
    }
  }

  async cancel(refundInfo, orderInfo) {
    const params = {
      after_sale_form_id: refundInfo.id,
      order_num: orderInfo.order_num
    }
    const res = await http.HPost(AIKUCUN_ORDER_CANCELAFTERSALE, params)
  }

  jumpLogistics(item) {
    const { orderId } = Taro.getCurrentInstance().router.params
    Taro.navigateTo({ url: '/main/order/aftersales/logistics?orderId=' + item.id + '&orderNum=' + orderId  })
  }

  // 格式化接口返回的日期
  getDateInfo(value) {
    const date = new Date(value)
    const y = date.getFullYear()
    let MM = date.getMonth() + 1
    MM = MM < 10 ? ('0' + MM) : MM
    let d = date.getDate()
    d = d < 10 ? ('0' + d) : d
    let h = date.getHours()
    h = h < 10 ? ('0' + h) : h
    let m = date.getMinutes()
    m = m < 10 ? ('0' + m) : m
    let s = date.getSeconds()
    s = s < 10 ? ('0' + s) : s
    return y + '-' + MM + '-' + d + ' ' + h + ':' + m + ':' + s
  }

  async onOpenmodel() {
    const res = await http.HGet(CONTENT_QR);
    this.setState({modalShow: true, qrImg: res.data})
  }

  handleCancel() {
    this.setState({modalShow: false})
  }

  render() {
    const {
      orderInfo,
      refundInfo,
      type,
      modalShow,
      qrImg,
    } = this.state
    if (!orderInfo) return
    return (
      <View className='after-sales-order-detail'>
        {Number(type) !== 6 && <View className='order-detail'>
          <View className='goods refund-info'>
            <View className='goods-title'>{refundInfo.status_name}</View>
            {/*<View className='refund-info-info'>
              <View className='refund-info-info-date'>{refundInfo.add_date}</View>
              <View className='refund-info-info-price'>
                <View className='price'><Text className='symbol'>￥</Text><View className='view-inline'><Float
                  value={orderInfo.total_fee}
                /></View></View>
              </View>
            </View>*/}
            {/*<View className='refund-info-tip'>钱款已退回至微信账户，您可在微信--[我]--[服务]中查看。</View>*/}
          </View>

          <View className='goods'>
            <View className='goods-title'>售后信息</View>
            <View className='goods-info'>
              <Image
                src={orderInfo.default_img_url}
              />
              <View>
                <View className='goods-info-title'>{orderInfo.product_name}</View>
                <View className='goods-info-price'>
                  <View>
                    <View className='price'><Text className='symbol'>￥</Text><View className='view-inline'><Float
                      value={orderInfo.total_fee}
                    /></View></View>
                  </View>
                  <View className='goods-info-num'>
                    x{orderInfo.buy_amount}
                  </View>
                </View>
              </View>
            </View>
            <View className='refund-detail'>
              <View className='refund-detail-item'>
                <View className='refund-detail-item-title'>退款原因</View>
                <View className='refund-detail-item-info'>{this.getReasonName(refundInfo.refund_reason)}</View>
              </View>
              <View className='refund-detail-item'>
                <View className='refund-detail-item-title'>退款金额</View>
                <View className='refund-detail-item-info orange'>
                  <View>
                    <View className='price'><Text className='symbol'>￥</Text><View className='view-inline'><Float
                      value={refundInfo.kedou_notice_refund_money ? refundInfo.kedou_notice_refund_money : refundInfo.refund_money}
                    /></View></View>
                  </View>
                </View>
              </View>
              <View className='refund-detail-item' style='margin-bottom:8px'>
                <View className='refund-detail-item-title'>申请件数</View>
                <View className='refund-detail-item-info'>
                  <View className='goods-info-num'>
                    {orderInfo.buy_amount}
                  </View>
                </View>
              </View>
              <View className='refund-detail-item'>
                <View className='refund-detail-item-title'>申请时间</View>
                <View className='refund-detail-item-info'>{this.getDateInfo(refundInfo.add_date)}</View>
              </View>
              <View className='refund-detail-item'>
                <View className='refund-detail-item-title'>退款编号</View>
                <View className='refund-detail-item-info'>{refundInfo.after_sale_no} |
                  <Text className='orange' onClick={this.copy.bind(this, refundInfo.after_sale_no)}>复制</Text>
                </View>
              </View>
            </View>
            <View className='refund-op'>
              {(process.env.P_ENV !== 'kd' || (process.env.P_ENV === 'kd' && qrImg === 'variable_code_close')) &&
              <View className='refund-op-btn' onClick={() => {
                Taro.navigateTo({url: `/distributor/contact/contact`})}}
              >客服介入</View>}
              {process.env.P_ENV === 'kd' && qrImg !== 'variable_code_close' &&
              <View className='refund-op-btn' onClick={this.onOpenmodel.bind(this)}>客服介入</View>}

              {refundInfo.status === 3 &&
              <View onClick={this.sureRefundPrice.bind(this, refundInfo, 1)} className='refund-op-btn'>确认退款金额</View>}
              {refundInfo.status === 3 &&
              <View onClick={this.sureRefundPrice.bind(this, refundInfo, 2)} className='refund-op-btn'>拒绝退款金额</View>}
            </View>
          </View>
        </View>}
        {Number(type) === 6 && <View className='order-detail'>
         {/* <View className='step'>
            <View className='step-item'>
              <View className='step-item-circular pass'></View>
              <View className='step-item-border pass'></View>
              <View className='step-item-info'>商家处理</View>
            </View>
            <View className='step-item'>
              <View className='step-item-circular fill'></View>
              <View className='step-item-border unpass'></View>
              <View className='step-item-info'>
                <View className='step-item-info-title'>寄回商品<Text>还剩6天23时58分</Text></View>
                <View className='step-item-info-subtitle'>请退货并填写物流信息</View>
                <View className='step-item-info-info'>
                  未与商家协商一致，请勿使用到付或平邮，以免商家拒签货物。<br/>
                  交易的钱款还在天猫中间账户，确保您资金安全请填写真实退货物流信息，逾期未填写，退货申请将关闭
                </View>
              </View>
            </View>
            <View className='step-item'>
              <View className='step-item-circular unpass'></View>
              <View className='step-item-border'></View>
              <View className='step-item-info'>商家退款</View>
            </View>
          </View>*/}

          <View className='address'>
            <View className='address-user'>
              收货人：
              {refundInfo.aikucun_notice_address && <Text>{JSON.parse(refundInfo.aikucun_notice_address).name}</Text>}
              {refundInfo.aikucun_notice_address && <Text>{JSON.parse(refundInfo.aikucun_notice_address).phone}</Text>}
            </View>
            {refundInfo.aikucun_notice_address &&
            <View>
              <View className='address-address'>
                <Text>{JSON.parse(refundInfo.aikucun_notice_address).address}</Text>
              </View>
              <View className='address-copy' onClick={this.copy.bind(this, JSON.parse(refundInfo.aikucun_notice_address).address)}>
                复制
              </View>
            </View>
            }

            <View className='jumpsend'>
              <View>
                <View className='jumpsend-title'>我已寄出</View>
                <View className='jumpsend-info'>点击填写物流单号</View>
              </View>
              <View className='jumpsend-btn' onClick={this.jumpLogistics.bind(this, refundInfo)}>填写单号</View>
            </View>
          </View>

          <View className='btn'>
            {(process.env.P_ENV !== 'kd' || (process.env.P_ENV === 'kd' && qrImg === 'variable_code_close')) &&
            <View className='btn-box' onClick={() => {
              Taro.navigateTo({url: `/distributor/contact/contact`})}}
            >客服介入</View>}
            {process.env.P_ENV === 'kd' && qrImg !== 'variable_code_close' &&
            <View className='btn-box' onClick={this.onOpenmodel.bind(this)}>客服介入</View>}
            <View onClick={this.cancel.bind(this, refundInfo, orderInfo)} className='btn-box'>撤销申请</View>
          </View>
        </View>}

        <AtModal className='modal_concatWx' isOpened={modalShow} onClose={this.handleCancel.bind(this)}>
          <AtModalHeader>联系客服</AtModalHeader>
          <AtModalContent>
            {!!qrImg && qrImg !== 'variable_code_close' && <Image
              mode='aspectFill'
              style='width: 120px;height: 120px;'
              src={qrImg}
            />}
          </AtModalContent>
          <AtModalAction>
            {process.env.TARO_ENV === 'h5' && <Text className='modal_txt'>
              有任何问题可添加，<br />您的专属顾问进行咨询
            </Text>}
            {process.env.TARO_ENV !== 'h5' && <Text className='modal_txt'>
              有任何问题可添加，\n 您的专属顾问进行咨询
            </Text>}
          </AtModalAction>
        </AtModal>
      </View>
    )
  }
}
